// pages/storeApply/storeApply.js
import * as API_Upload from '../../utils/fileUpload'
import * as API_Store from '../../api/store'
import * as API_Classify from '../../api/storeClassify'

const config = require('../../utils/config.js')
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min')
var qqMapSdk
Page({

  /**
   * 页面的初始数据
   */
  data: {
    back:false,
    // 最多选择多少个属性
    selectCount:100,
    //是否正在提交
    submitState:true,
    //直辖市列表
    cityList:['北京市','上海市','天津市','重庆市'],
    //商家分类
    classifyList:[],
    classifyIndex:0,
    showImg: [],
    storeApply:{
      storeClassify:null,
      storeImage:'',
      storeBacImage:'',
      businessImage:'',
      storeName:'',
      storePhone:'',
      addressName:'',
      brandDetail:'',
      consumption:null,
      serviceItem:'',
      businessStart:'10:30',
      businessEnd:'21:00',
      location:'请选择定位位置',
      provinceName:'',
      provinceCode:'',
      cityName:'', 
      cityCode:'',
      latitude:'',
      longitude:''
    }
   
  },

  //选择门店分类
  bindClassifyChange(e){
    let item = this.data.classifyList[e.detail.value]
    this.setData({
      classifyIndex: e.detail.value,
      'storeApply.storeClassify':item.id
    })
  },
  //选择定位
  changeLocation(){
    let that = this
    wx.chooseLocation({
      success: (res) => {
        qqMapSdk = new QQMapWX({
          key: config.QQMapKey
        });
        var latitude = res.latitude
        var longitude = res.longitude
        this.setData({'storeApply.location':res.name})
        qqMapSdk.reverseGeocoder({
          location:{latitude:latitude,longitude:longitude},
          complete(res){
            if(!res.status && res.status==0){
              const {ad_info} = res.result
              let provinceCode = ad_info.adcode.substr(0,2)+'0000'
              that.setData({
                'storeApply.adCode':ad_info.adcode,
                'storeApply.adName':ad_info.district,
                'storeApply.provinceName':ad_info.province,
                'storeApply.provinceCode':provinceCode,
                'storeApply.latitude':latitude+'',
                'storeApply.longitude':longitude+''
              })
              if(that.data.cityList.includes(ad_info.city)){
                let cityCode = ad_info.adcode.substr(0,2) + '0000'
                that.setData({
                  'storeApply.cityName':ad_info.district,
                  'storeApply.cityCode':cityCode,
                })
              }else{
                let cityCode = ad_info.adcode.substr(0,4) + '00'
                that.setData({
                  'storeApply.cityName':ad_info.city,
                  'storeApply.cityCode':cityCode,
                })
              }
            }else{
              wx.showToast({
                title: res,
                icon:'none',
                duration:50000
              })
            }
          }
        })
      },
      
      complete(res){
        console.log(res)
      }
    })
  },
  //赋值服务保障
  seviceSelect(e){
    let data = JSON.stringify(e.detail.data)
    this.setData({'storeApply.serviceItem':data})
  },
  businessStartChange: function(e) {
    this.setData({
      'storeApply.businessStart': e.detail.value
    })
  },
  businessEndChange: function(e) {
    this.setData({
      'storeApply.businessEnd': e.detail.value
    })
  },
  deleteShowImg(e) {
    const index = e.currentTarget.dataset.index
    const showImg = this.data.showImg
    showImg.splice(index,1)
    this.setData({
      showImg
    })
  },
  uploadImg: function (e) {
    
    var that = this;
    let img = e.currentTarget.dataset.img
    wx.showActionSheet({
     itemList: ['相册', '相机'],
     itemColor: "#40ba67",
     success: function (res) {
      if (!res.cancel) {
       if (res.tapIndex == 0) {
        that.chooseWxImageShop('album',img)
       } else if (res.tapIndex == 1) {
        that.chooseWxImageShop('camera',img)
       }
      }
     }
    })
   },
   chooseWxImageShop: function (type,img) {
    var that = this;
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: [type],
      success: function (res) {
        //门店形象照
        API_Upload.upload(res.tempFilePaths[0],res=>{
          const {url} = JSON.parse(res.data)
          if(img == 'img'){
            that.setData({'storeApply.storeImage':url})
          }else if(img == 'bacImg'){
            that.setData({'storeApply.storeBacImage':url})
          }else if(img == 'showimg'){
            const showImg = that.data.showImg
            showImg.push(url)
            that.setData({
              showImg
            })
            console.log(that.data.showImg)
          }
          else if(img = 'businessImg'){
            that.setData({'storeApply.businessImage':url})
          }
      },res=>{
          wx.showToast({
              title:'上传失败',
              icon:'none'
          })
      })
      }
    })
  },
  //更改门店名称
  changeStoreName(e){
    this.setData({'storeApply.storeName':e.detail.value})
  },
  //更改门店电话
  changeStorePhone(e){
    this.setData({'storeApply.storePhone':e.detail.value})
  },
  //更改门店地址
  changeAddressName(e){
    this.setData({'storeApply.addressName':e.detail.value})
  },
  //品牌介绍
  changeBrandDetail(e){
    this.setData({'storeApply.brandDetail':e.detail.value})
  },
  //人均消费
  changeConsumption(e){
    this.setData({'storeApply.consumption':e.detail.value})
  },
  //更改邀请码
  changeAgentCode(e){
    this.setData({'storeApply.agentCode':e.detail.value})
  },
  save(){
    let that = this
    that.setData({submitState:!that.data.submitState})
    let storeApply = that.data.storeApply
    
    if(!storeApply.storeImage.trim()){
      wx.showToast({title:'请上传门店logo',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.storeBacImage.trim()){
      wx.showToast({title:'请上传店内环境图',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.businessImage.trim()){
      wx.showToast({title:'请上传营业执照',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.storeName.trim()){
      wx.showToast({title:'请填写门店名称',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.storePhone.trim()){
      wx.showToast({title:'请填写门店电话',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.latitude.trim()){
      console.log(storeApply)
      wx.showToast({title:'请选择门店定位',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.addressName.trim()){
      wx.showToast({title:'请填写门店地址',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.brandDetail.trim()){
      wx.showToast({title:'请填写品牌介绍',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else if(!storeApply.consumption){
      wx.showToast({title:'请填写人均消费',duration:1500,icon:'none'})
      that.setData({submitState:!that.data.submitState})
    }else{
      try{
        storeApply.consumption=parseInt(storeApply.consumption);
        if(Number.isNaN( storeApply.consumption)){
          wx.showToast({title:'人均消费只能为数字',duration:1500,icon:'none'})
          that.setData({submitState:!that.data.submitState,'storeApply.consumption':''})
          return;
        }
      }catch(err){
        wx.showToast({title:'人均消费只能为数字',duration:1500,icon:'none'})
        that.setData({submitState:!that.data.submitState,'storeApply.consumption':''})
        return;
      }
      if(that.data.showImg.length > 0) {
        storeApply.storeShowImage = that.data.showImg.join(',')
      }
      //修改
      if(storeApply.id){
        console.log(storeApply)
        API_Store.update(storeApply).then(res =>{
          that.applyEnd()
        })
      }else{
        //新增
        API_Store.create(storeApply).then(res =>{
          wx.showToast({
            title: '申请成功',
            duration:1500,
            success(res){
              setTimeout(function () {
                wx.redirectTo({
                  url: '../storeApplyResult/storeApplyResult',
                })
            },1500)
            }
          })
        })
      }
    }
  },
  //申请结束 
  applyEnd(){
    wx.showToast({
      title: '申请成功',
      duration:1500,
      success(res){
        setTimeout(function () {
          wx.navigateBack({
            delta: 0,
          })
      },1500)
      }
    })
    
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    // if(options.back){
    //都需要有返回
    this.setData({back:true})
    // }
    //加载服务保障可选项
    this.choiceGuige = this.selectComponent("#serviceItem");
    //加载分类数据

    API_Classify.getClassifyFirst().then(res =>{
      API_Store.getApply().then(ref =>{
        if(ref){
          for(var i = 0; i < res.length; i++){
            if(res[i].id == ref.storeClassify){
              this.setData({classifyIndex:i})
              break
            }
          }
          this.setData({
            classifyList:res,
            storeApply:ref
          })
          let e = {
            key:'jy_service_item',
            title:'选择服务保障',
            selected:ref.serviceItem
          }
          this.choiceGuige.loadDic(e)
          if(ref.storeShowImage) {
            const showImg =  ref.storeShowImage.split(',')
            this.setData({
              showImg
            })
          }
        }else{
          let e = {
            key:'jy_service_item',
            title:'选择服务保障'
          }
          this.choiceGuige.loadDic(e)
          this.setData({
            classifyList:res,
            'storeApply.storeClassify':res[0].id
          })

        }
      })
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

   
})